import axios from 'axios'
import store from '../store'
import router from '../router'
const ajax = axios.create({
  baseURL: 'http://toutiao.itheima.net'// 设置基地址
})
// 请求拦截器
ajax.interceptors.request.use(config => {
  if (store.state.token) {
    config.headers.Authorization = `Bearer ${store.state.token}`
  }
  return config
}, err => {
  console.dir(err)
})
// 响应拦截器(数据处理和拦截权限)
ajax.interceptors.response.use(res => {
  return res.data
}, error => {
  console.dir(error)
  if (error.response.status === 401) {
    store.commit('setToken', '')
    router.replace({
      path: '/login?qu=' + router.currentRoute.path
    })
  }
  return Promise.reject(error)
})
export default ajax
